#include "jpsocket.h"

JpSocket::JpSocket(QObject *parent) : QObject(parent)
{

}

JpSocket::~JpSocket()
{

}



void JpSocket::clientInit(){
     //qsrand(time(0));

     //_serverport=20000+qrand()%(80000-20000);
     _serverport=11104;
     client = new QTcpSocket(this);
     client->connectToHost(QHostAddress(_serverip), _serverport);
     connect(client, SIGNAL(readyRead()), this, SLOT(readClient()));
     qDebug() << "客户端启动,连接服务端ip:"<<_serverip<<",连接服务端端口号:"<<_serverport;
}


void JpSocket::serverInit(){

    server = new QTcpServer(this);
    //qsrand(time(0));

    //_port=20000+qrand()%(80000-20000);
    _port=11104;

    QHostAddress address(_ip);


    if(!server->listen(address, _port))
    {
        qDebug() << "服务器启动不了!";
    }
    else
    {
        connect(server, SIGNAL(newConnection()), this, SLOT(jpnewConnection()));
        qDebug() << "服务器启动!使用端口:"<<_port;
    }

}
void JpSocket::JPConnectionDisconnect(){
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    serverDisConnectionLogic(socket);

}
void JpSocket::jpnewConnection(){
    QTcpSocket *socket = server->nextPendingConnection();
    connect(socket,SIGNAL(disconnected()),this,SLOT(JPConnectionDisconnect()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readServer()));
    if(socket==0){
        qDebug() << "客户端连接失败!";
    }
    this->serverConnectionLogic(socket);
}
void JpSocket::readClient(){
    readClientLogic();
}
void JpSocket::readServer(){
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    readServerLogic(socket);
}
void JpSocket::readClientLogic(){

}
void JpSocket::readServerLogic(QTcpSocket* socket){
    qDebug()<<"(父类)"<<socket->peerAddress().toString();
}

void JpSocket::serverConnectionLogic(QTcpSocket *sk){
    qDebug() << "(父类)客户端IP："<<sk->peerAddress().toString()<<",客户端口:"<<sk->peerPort();
}

void JpSocket::serverDisConnectionLogic(QTcpSocket *sk){
    qDebug()<<"客户端断开连接"<<sk->peerAddress().toString();
}

